# CNV frequency---------
# snv_stat <- data.table::fread("/Pub/Users/wangyk/project/Poroject/P211229003_F211213003_AML_Necroptosis/data/TCGA-LAML.gistic.tsv.id_converted.txt") %>%
#     as.data.frame()
# CNV_df <- head(snv_stat, 20)

#'
#' @TODO CNV
#' @title : # this is tittle
#' @description: 
#' @details : firse line
#' @param : 
#' @param 1: 
#' @param 2: 
#' @param 3: 
#' @param 4: 
#' @param 5: 
#' @param 6: 
#' @param 7: 
#' @param 8: 
#' @param 9: 
#' @param seed: 
#' @param saveplot: 
#' @return:  a list
#' @examples: 
#' @author: *WYK*
#'
CNV_Freq_Dumbbell_Chart <- function(CNV_df = NULL, gene_col = "Gene", od = NULL,
    var_name = NULL, w = 11, h = 4, h_plot = F, ...) {

    require(tidyverse)
    require(ggpubr)

    colnames(CNV_df)[which(colnames(CNV_df) == gene_col)] <- "Gene"

    snv_stat_summary <- CNV_df %>%
        # filter(Gene %in% xgene) %>%
    pivot_longer(cols = -Gene, values_to = "cnv_freq", names_to = "sample") %>%
        group_by(Gene, cnv_freq) %>%
        summarise(n = n()) %>%
        filter(cnv_freq != 0) %>%
        mutate(cnv_freq = ifelse(cnv_freq == 1, "GAIN", "LOSS")) %>%
        pivot_wider(names_from = "cnv_freq", values_from = "n") %>%
        mutate(LOSS = replace_na(LOSS, 0), GAIN = replace_na(GAIN, 0)) %>%
        mutate(LOSS = round(LOSS/ncol(CNV_df), 4) * 100, GAIN = round(GAIN/ncol(CNV_df),
            2) * 100)

    p <- snv_stat_summary %>%
        pivot_longer(cols = -c(Gene), values_to = "perctenge", names_to = "Type") %>%
        ggplot(aes(x = perctenge, y = fct_reorder(Gene, perctenge, .desc = TRUE))) +
        geom_line(aes(group = Gene), size = 2.5, alpha = 0.7, color = "grey") + geom_point(aes(color = Type),
        size = 2.7) + ggpubr::theme_pubr(12) + labs(x = "CNV.frequency(*100%)", y = "Gene") +
        scale_color_manual(values = c("#E12F1D", "#4F9CCC"))


    if (isFALSE(h_plot)) {
        p <- p
    } else if (isTRUE(h_plot)) {
        p <- p + coord_flip() + theme(axis.text.x.bottom = element_text(angle = 45,
            hjust = 1, vjust = 1, size = 8))
    }

    if (!is.null(od)) {
        if (is.null(var_name)) {
            var_name <- str_glue("{Sys.time() %>% format.Date()}") %>%
                as.character()
        }

        ggsave(plot = p, file = str_glue("{od}/Figure_CNV_CNV_Freq_Dumbbell_Chart_{var_name}.pdf"),
            width = w, height = h)
    }

    return(p)
}
# ---------


# # cnv绘图临时暂存，待处理------
# cnv <- read.delim("TCGA-BRCA.gistic.tsv.gz")
# gene <- read.delim("gencode.v22.annotation.gene.probeMap")
# chrom_size <- read.delim("hg19.chrom.sizes", header = F)
# chrom_size <- chrom_size[1:24, ]

# gene_ID <- gene[, 1:2]
# cnv <- merge(cnv, gene_ID, by.x = "Gene.Symbol", by.y = "id")
# cnv <- cnv[, c(1108, 2:1107)]

# low_name <- intersect(names(cnv), rownames(dat)[dat$G == "low"])
# high_name <- intersect(names(cnv), rownames(dat)[dat$G == "high"])

# high_cnv <- cnv[, c("gene", high_name)]
# low_cnv <- cnv[, c("gene", low_name)]

# high_cnv[high_cnv == -1] <- NA
# h1 <- rowSums(high_cnv[, -1], na.rm = TRUE)
# high_cnv[is.na(high_cnv)] <- -1
# high_cnv[high_cnv == 1] <- NA
# h2 <- rowSums(high_cnv[, -1], na.rm = TRUE)
# high_cnv[is.na(high_cnv)] <- 1

# low_cnv[low_cnv == -1] <- NA
# l1 <- rowSums(low_cnv[, -1], na.rm = TRUE)
# low_cnv[is.na(low_cnv)] <- -1
# low_cnv[low_cnv == 1] <- NA
# l2 <- rowSums(low_cnv[, -1], na.rm = TRUE)
# low_cnv[is.na(low_cnv)] <- 1

# cnv <- cnv[, c("gene", high_name, low_name)]
# cnv[cnv == -1] <- NA
# gain <- colSums(cnv[, -1], na.rm = TRUE)
# cnv[is.na(cnv)] <- -1
# cnv[cnv == 1] <- NA
# loss <- colSums(cnv[, -1], na.rm = TRUE)
# cnv[is.na(cnv)] <- 1


# dat_plot2 <- data.frame(gene = cnv$gene, high_gain = h1, high_loss = h2, low_gain = l1,
#     low_loss = l2)

# dat_plot2 <- aggregate(dat_plot2[, -1], by = list(dat_plot2$gene), sum)
# rownames(dat_plot2) <- dat_plot2$Group.1
# dat_plot2 <- dat_plot2[, -1]

# gene <- subset(gene, gene %in% rownames(dat_plot2))
# gene$high_gain <- dat_plot2[gene$gene, "high_gain"]
# gene$high_loss <- dat_plot2[gene$gene, "high_loss"]
# gene$low_gain <- dat_plot2[gene$gene, "low_gain"]
# gene$low_loss <- dat_plot2[gene$gene, "low_loss"]

# data1 <- data.frame(chrom = chrom_size$V1, chromStart = chrom_size$V2, high_gain = rep(0,
#     24), high_loss = rep(0, 24))

# library(reshape2)
# library(stringr)
# library(ggplot2)
# library(patchwork)
# dat_plot <- gene[, c(-1, -6)]
# a <- dat_plot[c(2, 3, 5, 6)]
# a <- rbind(a, data1)
# a <- melt(a, id.vars = c("chrom", "chromStart"))
# a$variable <- str_split_fixed(a$variable, "_", 2)[, 2]
# a$chrom <- factor(a$chrom, levels = c("chr1", "chr2", "chr3", "chr4", "chr5", "chr6",
#     "chr7", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15",
#     "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX", "chrY"),
#     ordered = TRUE)

# data2 <- data.frame(chrom = chrom_size$V1, chromStart = chrom_size$V2, low_gain = rep(0,
#     24), low_loss = rep(0, 24))
# b <- dat_plot[c(2, 3, 7, 8)]
# b <- rbind(b, data2)

# b <- melt(b, id.vars = c("chrom", "chromStart"))

# b$variable <- str_split_fixed(b$variable, "_", 2)[, 2]
# b$chrom <- factor(b$chrom, levels = c("chr1", "chr2", "chr3", "chr4", "chr5", "chr6",
#     "chr7", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15",
#     "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX", "chrY"),
#     ordered = TRUE)


# p1 <- ggplot(a, aes(x = chromStart, y = value, fill = variable, color = variable)) +
#     geom_col(position = "identity", size = 0.25) + facet_wrap(~chrom, ncol = 24,
#     strip.position = "bottom") + theme_bw() + theme(strip.text = element_blank(),
#     legend.position = "none", panel.grid = element_blank(), axis.title.x = element_blank(),
#     axis.text.x = element_blank(), strip.background = element_blank(), strip.placement = "outside",
#     axis.ticks.x = element_blank()) + scale_fill_manual(name = "", values = c("#E74C3C",
#     "#2980B9")) + scale_color_manual(name = "", values = c("#E74C3C", "#2980B9")) +
#     labs(x = "", y = "Frequency")

# p2 <- ggplot(b, aes(x = chromStart, y = value, fill = variable, color = variable)) +
#     geom_col(position = "identity", size = 0.25) + facet_wrap(~chrom, ncol = 24,
#     strip.position = "bottom") + theme_bw() + theme(panel.grid = element_blank(),
#     axis.title.x = element_blank(), axis.text.x = element_blank(), strip.background = element_blank(),
#     strip.placement = "outside", axis.ticks.x = element_blank()) + scale_fill_manual(name = "",
#     values = c("#E74C3C", "#2980B9")) + scale_color_manual(name = "", values = c("#E74C3C",
#     "#2980B9")) + labs(x = "", y = "Frequency")

# p1/p2

# library(ggbeeswarm)
# library(ggpubr)
# dat_plot1 <- data.frame(gain = gain, loss = -loss)
# dat_plot1$Group <- dat[rownames(dat_plot1), "G"]
# dat_plot1 <- melt(dat_plot1, id.vars = "Group")
# ggplot(dat_plot1, aes(x = Group, y = value, fill = Group)) + geom_quasirandom(method = "quasirandom",
#     size = 2, width = 0.3, shape = 21, stroke = 0, color = "#566573") + theme_classic() +
#     theme(legend.position = "none", panel.grid = element_blank()) + stat_compare_means(label.y = 14000,
#     label.x = 0.7) + stat_summary(fun = median, fun.min = median, fun.max = median,
#     geom = "crossbar", width = 0.15, size = 0.3, color = "black") + stat_summary(fun.data = function(x) median_hilow(x,
#     0.5), geom = "errorbar", width = 0.2, size = 1, color = "black") + labs(x = "",
#     y = "Frequency") + scale_x_discrete(breaks = c("high", "low"), labels = c("High Risk",
#     "Low Risk"))

# # ---------

# bar_p <- coef_file %>%
#     mutate(group = ifelse(coef < 0, "a", "b")) %>%
#     ggplot() + geom_col(aes(x = coef, y = fct_reorder(signature, coef), fill = group),
#     width = 0.65) + ggpubr::theme_pubclean(14) + labs(y = "Gene") + ggsci::scale_fill_jama() +
#     theme(legend.position = "none", axis.ticks.y.left = element_blank(), axis.line.x.bottom = element_line(color = "black"))


# ggsave(plot = bar_p, file = file.path(out_home, "out/Figure_coef.pdf"), width = 3,
#     height = 4)
